package site.assad.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import site.assad.domain.Game;
import site.assad.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2017/12/15 11:05
 * Description:
 */
@Repository
public class GameDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    //验证game是否存在
    public boolean checkGameById(final int gameId){
        final String sql = "SELECT COUNT(game_id) " +
                "FROM games_item " +
                "WHERE game_id = ?";
        int result = jdbcTemplate.queryForObject(sql,new Object[]{gameId},Integer.class);
        return result > 0;
    }



    //game collected
    public void gameCollected(final Game game,final User user){
        final String sql = "update games_item " +
                "set collected_count = collected_count + 1 " +
                "where game_id = ? and user_id = ?";
        jdbcTemplate.update(sql,new Object[]{game.getId(),user.getId()});
    }


    //get game
    public Game getGameById(final int id){
        final String sql = "SELECT (game_id,game_name,collected_count " +
                "FROM games_item WHERE game_id = ?";

        Game game = new Game();

        jdbcTemplate.query(sql,new Object[]{id}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                game.setId(rs.getInt("game_id"));
                game.setName(rs.getString("game_name"));
                game.setCollectedCount(rs.getInt("collected_count"));
            }
        });
        return game;
    }

    //延迟加载 game 的 users 数据域
    public List<User> getCollectUserList(final Game game){

        final String sql2 = "SELECT (users.user_id,users.user_name,users.user_password,users.user_icon) " +
                "FROM users " +
                "WHERE users.user_id = (SELECT games_collect.user_id WHERE games_collect.game_id = ?)";
        List<User> userList = null;
        userList = jdbcTemplate.query(sql2, new Object[]{game.getId()}, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setId(rs.getInt("users.user_id"));
                user.setName(rs.getString("users.user_name"));
                user.setPassword(rs.getString("users.user_password"));
                user.setIcon(rs.getString("users.user_icon"));
                return user;
            }
        });


        return userList;
    }




}
